package com.last1mile.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.last1mile.commons.PwdEnDe;
import com.last1mile.commons.UserTypeEnum;
import com.last1mile.dao.interfaces.UserDao;
import com.last1mile.model.Customer;
import com.last1mile.pojo.UserDO;
import com.last1mile.service.UserService;

@Component("userServiceImpl")
public class UserServiceImpl implements UserService {

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    @Autowired
    @Qualifier("pwdEnDe")
    private PwdEnDe pwdEnDe;

    @Override
    public void createUser(Customer customer) {
        if (customer != null) {
            UserDO userDo = new UserDO();
            userDo.setLoginId(customer.getLoginId());
            String[] pwdPair = pwdEnDe.encrypt(customer.getLoginPwd());
            userDo.setLoginPwd(pwdPair[0]);
            userDo.setPwdKey(pwdPair[1]);
            userDo.setSurname(customer.getSurname());
            userDo.setLastname(customer.getLastname());
            userDo.setSex(customer.getSex());
            userDo.setEmail(customer.getEmail());
            userDo.setUserType(UserTypeEnum.PERSONAL.getValue());
            this.userDao.inserUser(userDo);
        }
    }

    @Override
    public UserDO queryUserByLoginIdPwd(String loginId, String loginPwd) {
        UserDO resultUserDo = null;

        if (StringUtils.isNotBlank(loginId) && StringUtils.isNotBlank(loginPwd)) {
            UserDO querUserDo = new UserDO();
            querUserDo.setLoginId(loginId);
            querUserDo.setLoginPwd(loginPwd);
            resultUserDo = this.userDao.queryUser(querUserDo);
        }

        return resultUserDo;
    }

    public UserDO queryUserByLoginId(String loginId) {
        UserDO resultUserDo = null;
        if (StringUtils.isNotBlank(loginId)) {
            UserDO queryUserDo = new UserDO();
            queryUserDo.setLoginId(loginId);
            resultUserDo = this.userDao.queryUser(queryUserDo);
        }

        return resultUserDo;
    }

    @Override
    public UserDO queryUserById(Integer id) {
        UserDO resultUserDo = null;
        if (id != null) {
            UserDO queryUserDo = new UserDO();
            queryUserDo.setId(id);
            resultUserDo = this.userDao.queryUser(queryUserDo);
        }

        return resultUserDo;
    }

    @Override
    public void updateUserPic(Integer userId, String userPicDir) {
        if((userId != null)&&(StringUtils.isNotBlank(userPicDir))){
            UserDO userDo = new UserDO();
            userDo.setId(userId);
            userDo.setPic(userPicDir);
            this.userDao.updateUser(userDo);
        }
    }

}
